package cn.nfwx.tv.controller.me;

import android.app.Dialog;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.Display;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;

import java.util.ArrayList;
import java.util.List;

import cn.nfwx.tv.R;
import cn.nfwx.tv.callback.ResponseWithFailListener;
import cn.nfwx.tv.helper.AccountHelper;
import cn.nfwx.tv.manager.UserManager;
import cn.nfwx.tv.model.Result;
import cn.nfwx.tv.util.AppUtil;
import cn.nfwx.tv.util.GlideUtil;
import cn.nfwx.tv.util.ToastUtil;
import cn.nfwx.tv.widget.ItemSettingView;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

import static cn.nfwx.tv.fragment.me.MineFragment.POSITION_ABOUT;
import static cn.nfwx.tv.fragment.me.MineFragment.POSITION_APPOINT;
import static cn.nfwx.tv.fragment.me.MineFragment.POSITION_DOWNLOAD;
import static cn.nfwx.tv.fragment.me.MineFragment.POSITION_HISTORY;
import static cn.nfwx.tv.fragment.me.MineFragment.POSITION_SHARE;
import static cn.nfwx.tv.fragment.me.MineFragment.POSITION_SUBSCRIPT;

public final class MineLeftController implements View.OnClickListener {

    private FragmentActivity mAcitivty;
    View mView;

    OnMineClickListener onMineClickListener;

    private TextView user_name;

    List<ItemSettingView> itemMine = new ArrayList<>();
    private TextView nick_name_edit;
    private Dialog nickDialog;
    private Disposable mDisposable;

    public MineLeftController(FragmentActivity activity, View view) {
        mView = view;
        mAcitivty = activity;
        initView();
        initListen();
        loadData();
    }


    public void initView() {
        GlideUtil.loadCircleImage(mView.getContext(), R.mipmap.mine_head, (ImageView) finView(R.id.user_head));

        user_name = finView(R.id.user_name);
        itemMine.clear();
        itemMine.add((ItemSettingView) finView(R.id.subscription_layout));
        itemMine.add((ItemSettingView) finView(R.id.appointment_layout));
        itemMine.add((ItemSettingView) finView(R.id.history_layout));
        itemMine.add((ItemSettingView) finView(R.id.mydownload_layout));
        itemMine.add((ItemSettingView) finView(R.id.share_layout));
        itemMine.add((ItemSettingView) finView(R.id.about_layout));
        itemMine.add((ItemSettingView) finView(R.id.zixun_layout));

        refreshLogout();
    }

    public void refreshLogout() {
        if (AccountHelper.getInstance().isLogin(mView.getContext())) {
            finView(R.id.btn_logout).setVisibility(View.VISIBLE);
        } else {
            finView(R.id.btn_logout).setVisibility(View.GONE);
        }
    }

    private void initListen() {
        finView(R.id.back_btn).setOnClickListener(this);
        finView(R.id.login_btn).setOnClickListener(this);
        finView(R.id.register_tbn).setVisibility(View.GONE);
        finView(R.id.register_tbn).setOnClickListener(this);
        finView(R.id.zixun_layout).setOnClickListener(this);
        finView(R.id.subscription_layout).setOnClickListener(this);
        finView(R.id.appointment_layout).setOnClickListener(this);
        finView(R.id.history_layout).setOnClickListener(this);
        finView(R.id.mydownload_layout).setOnClickListener(this);
        finView(R.id.about_layout).setOnClickListener(this);
        finView(R.id.setting_layout).setOnClickListener(this);
        finView(R.id.share_layout).setOnClickListener(this);
        finView(R.id.btn_logout).setOnClickListener(this);
        finView(R.id.user_name).setOnClickListener(this);
    }

    private void loadData() {
        refreshLoginStats();
    }

    /**
     * 刷新登录状态
     */
    public void refreshLoginStats() {
        if (AccountHelper.getInstance().isLogin(mView.getContext())) {
            user_name.setText(AccountHelper.getInstance().getNick(mView.getContext()));
            if (!TextUtils.isEmpty(AccountHelper.getInstance().getLogo(mView.getContext()))) {
                GlideUtil.loadCircleImage(mView.getContext(), AccountHelper.getInstance().getLogo(mView.getContext()), (ImageView) finView(R.id.user_head));
            }
            user_name.setVisibility(View.VISIBLE);
            finView(R.id.login_btn).setVisibility(View.GONE);
            finView(R.id.register_tbn).setVisibility(View.GONE);
            finView(R.id.v_spilt).setVisibility(View.GONE);
        } else {
            user_name.setVisibility(View.GONE);
            finView(R.id.login_btn).setVisibility(View.VISIBLE);
            finView(R.id.register_tbn).setVisibility(View.VISIBLE);
            finView(R.id.v_spilt).setVisibility(View.VISIBLE);
        }
        refreshLogout();
    }

    public <T extends View> T finView(int rid) {
        return mView.findViewById(rid);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back_btn:
                if (onMineClickListener != null) {
                    onMineClickListener.close();
                }
                break;
            case R.id.login_btn:
                if (onMineClickListener != null) {
                    onMineClickListener.login();
                }
                break;
            case R.id.register_tbn:
                if (onMineClickListener != null) {
                    onMineClickListener.register();
                }
                break;
            case R.id.zixun_layout:
                if (onMineClickListener != null) {
                    onMineClickListener.zixun();
                }
                break;
            case R.id.subscription_layout:
                if (onMineClickListener != null) {
                    onMineClickListener.subscript();
                }
                break;
            case R.id.appointment_layout:
                if (onMineClickListener != null) {
                    onMineClickListener.appoint();
                }
                break;
            case R.id.history_layout:
                if (onMineClickListener != null) {
                    onMineClickListener.history();
                }
                break;
            case R.id.mydownload_layout:
                if (onMineClickListener != null) {
                    onMineClickListener.download();
                }
                break;
            case R.id.about_layout:
                if (onMineClickListener != null) {
                    onMineClickListener.about();
                }
                break;
            case R.id.setting_layout:
                if (onMineClickListener != null) {
                    onMineClickListener.setting();
                }
                break;
            case R.id.share_layout:
                if (onMineClickListener != null) {
                    onMineClickListener.share();
                }
                break;
            case R.id.btn_logout://登出
                if (onMineClickListener != null) {
                    onMineClickListener.logout();
                }
                break;
            case R.id.user_name:
                if (AccountHelper.getInstance().isLogin(mView.getContext())) {
                    View dialogView = View.inflate(mView.getContext(), R.layout.dialog_nickname, null);
                    nick_name_edit = dialogView.findViewById(R.id.nick_name_edit);
                    nick_name_edit.setText(AccountHelper.getInstance().getNick(mView.getContext()));
                    Button nick_commit_btn = dialogView.findViewById(R.id.nick_commit_btn);
                    nick_commit_btn.setOnClickListener(this);
                    nickDialog = getDialog(dialogView);
                    if (nickDialog != null) {
                        nickDialog.show();
                    }
                }
                break;
            case R.id.nick_commit_btn:
                final String nickName = nick_name_edit.getText().toString().trim();
                if (TextUtils.isEmpty(nickName)) {
                    Toast.makeText(mView.getContext(), "昵称不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (nickName.length() > 10) {
                    Toast.makeText(mView.getContext(), "限10字内", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (nickName.equals(AccountHelper.getInstance().getNick(mView.getContext()))) {
                    Toast.makeText(mView.getContext(), "昵称未改变，请先修改", Toast.LENGTH_SHORT).show();
                    return;
                }
                UserManager.requestIjkchangeNick(mView.getContext(), nickName, new ResponseWithFailListener<String>() {
                    @Override
                    public void onResponse(String requestTag, final String response) {
                        Observable.create(new ObservableOnSubscribe<Result>() {
                            @Override
                            public void subscribe(ObservableEmitter<Result> emitter) throws Exception {
                                Result result = JSON.parseObject(response, new TypeReference<Result>() {
                                }.getType());
                                emitter.onNext(result);
                                emitter.onComplete();
                            }
                        }).subscribeOn(Schedulers.io())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(new Observer<Result>() {
                                    @Override
                                    public void onSubscribe(Disposable d) {
                                        mDisposable = d;
                                    }

                                    @Override
                                    public void onNext(Result result) {
                                        if (result.getMessage().equals(Result.RESULT_SUCCESS)) {
                                            ToastUtil.show(mView.getContext(), "修改成功");
                                            AccountHelper.getInstance().saveNick(mView.getContext(), nickName);
                                            refreshLoginStats();
                                            nickDialog.dismiss();
                                        } else {
                                            ToastUtil.show(mView.getContext(), "修改失败");
                                        }
                                    }

                                    @Override
                                    public void onError(Throwable e) {

                                    }

                                    @Override
                                    public void onComplete() {

                                    }
                                });
                    }

                    @Override
                    public void onError(String requestTag, Throwable t) {

                    }

                    @Override
                    public void onFinish() {

                    }

                    @Override
                    public void onFail(String requestTag, String response) {

                    }
                });
                break;
        }
    }

    public Dialog getDialog(View view) {
        Dialog dialog = new Dialog(mView.getContext(), R.style.MyDialog);
        dialog.setContentView(view);
        Window dialogWindow = dialog.getWindow();
        WindowManager m = mAcitivty.getWindowManager();
        Display d = m.getDefaultDisplay(); // 获取屏幕宽、高度
        WindowManager.LayoutParams p = dialogWindow.getAttributes(); // 获取对话框当前的参数值
        p.height = (int) (d.getHeight() * 0.5); // 高度设置为屏幕的0.6，根据实际情况调整
        p.width = (int) (d.getWidth() * 0.6); // 宽度设置为屏幕的0.65，根据实际情况调整
        dialogWindow.setAttributes(p);
        return dialog;
    }

    private void showSelectItem() {
        for (ItemSettingView itemSettingView : itemMine) {
            itemSettingView.setSelected(false);
        }
    }


    private void showSelectItem(View v) {
        for (ItemSettingView itemSettingView : itemMine) {
            if (itemSettingView.getId() == v.getId()) {
                itemSettingView.setSelected(true);
            } else {
                itemSettingView.setSelected(false);
            }
        }
    }

    public OnMineClickListener getOnMineClickListener() {
        return onMineClickListener;
    }

    public void setOnMineClickListener(OnMineClickListener onMineClickListener) {
        this.onMineClickListener = onMineClickListener;
    }

    public void showItem(int index) {
        switch (index) {
            case POSITION_SUBSCRIPT:
                showSelectItem(finView(R.id.subscription_layout));
                break;
            case POSITION_APPOINT:
                showSelectItem(finView(R.id.appointment_layout));
                break;
            case POSITION_HISTORY:
                showSelectItem(finView(R.id.history_layout));
                break;
            case POSITION_DOWNLOAD:
                showSelectItem(finView(R.id.mydownload_layout));
                break;
            case POSITION_SHARE:
                showSelectItem(finView(R.id.share_layout));
                break;
            case POSITION_ABOUT:
                showSelectItem(finView(R.id.about_layout));
                break;
            case -1:
                showSelectItem();
                break;
        }
    }

    public interface OnMineClickListener {
        void close();

        void login();

        void register();

        void zixun();

        void subscript();

        void appoint();

        void history();

        void download();

        void about();

        void setting();

        void logout();

        void share();
    }

    public void release() {
        itemMine.clear();
        onMineClickListener = null;
        if (nickDialog != null) {
            if (nickDialog.isShowing()) {
                nickDialog.dismiss();
            }
        }
        nickDialog = null;
        mAcitivty = null;
        if (mDisposable != null) {
            if (!mDisposable.isDisposed()) {
                mDisposable.dispose();
            }
        }
    }
}
